<?php
namespace Weibo\Controller;
use Common\Controller\FrontbaseController;
class WeibobaseController extends FrontbaseController {

	protected $user;				//当前用户数据,结构对应本模块的数据表
	protected $userId;				//当前用户ID

	protected $super = FALSE;		//是否超级权限

	public function _initialize(){
		parent::_initialize();
		
		if (NEWTEST === TRUE) {
			$user = array();
			if ($_REQUEST['user_id']) {
				$user = translate_field('User', \User\Lib\ImiLib::getUserById($_REQUEST['user_id']));
				$weibo_user = D('WeiboUser') -> getUserById($this -> userId);
				
				$this -> user = array_merge($this -> user, $weibo_user);
				$this -> userId = $this -> user['user_id'];
			}
			return;
		}
		
		//检测用户登录状态,本模块所有操作都要求必需登录
		\User\Lib\ImiLib::checkLogin($this);

		//从User模块获取当前登录的用户数据
		$this -> user = translate_field('User', \User\Lib\ImiLib::getCurrentUser());
		$this -> userId = \User\Lib\ImiLib::getCurrentUserId();
		
		//For Test
		//$this -> userId = 14;
		
		$weibo_user = D('WeiboUser') -> getUserById($this -> userId);
		
		//如果当前微博用户表中无此用户,插入
		if ($weibo_user !== FALSE && !$weibo_user) {		//不是查询失败且没有结果
			
			$weibo_user = array(
					'user_id' => $this -> userId,
					'nickname' => $this -> user['nickname'] ?: '未命名' . substr(md5(NOW_TIME . mt_rand(1000, 9999)), 0, 6),
					'introduction' => $this -> user['introduction'],
					'weibo_count' => 0,
					'follow_count' => 0,
					'fans_count' => 0,
					'verify' => 0,
					'activity_time' => NOW_TIME,
					'status' => 1,
			);
			
			D('WeiboUser') -> add($weibo_user);
			
		}
		
		//合并用户数据
		$this -> user = array_merge($this -> user, $weibo_user);
		
		//TODO 实现超级权限机制
	}
	
	/**
	 * 检测权限
	 * 是否已停用的帐户
	 * 是否在对方黑名单中(微博作者或评论作者)
	 * @param array $data
	 */
	public function checkWeiboPermission($data = array(), $return = FALSE){
		
		$result = array(
			'error' => FALSE,
			'error_msg' => '',
		);
		
		if (isset($data['user_id'])) {
			$is_black = D('WeiboUserBlacklist') -> where(array('user_id' => $data['user_id'], 'target_id' => $this -> userId)) -> count(); 
			if ($is_black) {
				$result['error'] = TRUE;
				$result['error_msg'] = '您在对方的黑名单中无法执行此操作';
			}
		}
		
		if (!$result['error']) {
			if (!$this -> user['status']) {
				$result['error'] = TRUE;
				$result['error_msg'] = '您的帐户已停用无法执行此操作';
			}
		}
		
		if ($return) {
			
			return $result;
			
		} elseif($result['error']) {
			$this -> output(array(
					'error' => 202,
					'error_msg' => $result['error_msg'],
			));
		}
	}

}
